import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '/src/store'

Vue.use(VueRouter)

// 路由表
const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login.vue')
  }
  , {
    path: '/',
    name: 'index',
    component: () => import('../views/index.vue'),
    children: [
      //系统设置
      { path: '/system/info', name: 'systeminfo', component: () => import('../views/system/info.vue') },

      { path: '/users', name: 'users', component: () => import('../views/users/list.vue') },
      { path: '/users/add', name: 'usersadd', component: () => import('../views/users/add.vue') },

      { path: '/goods', name: 'goods', component: () => import('../views/goods/list.vue') },
      { path: '/goods/add', name: 'goodsadd', component: () => import('../views/goods/add.vue') },
      { path: '/goods/edit/:id', name: 'goodsedit', component: () => import('../views/goods/edit.vue') },
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes  //路由表
})

// 导航守卫
router.beforeEach((to, from, next) => {
  //持久化用户状态
  let user = JSON.parse(sessionStorage.getItem('user'));
  store.commit('setUser', user);

  //判断是否登录（从vuex 中获取保存的 用户id） 排除掉登录页面
  if (store.state.user != null && store.state.user.uersID != 0 || to.path == '/login') {
    next(); //放行
  } else {
    router.push({ path: '/login' })
  }
})

export default router
